//
//  QWLoginController.m
//  qwm
//
//  Created by kevin on 2023/3/24.
//

#import "QWLoginController.h"
#import "QWLoginCell.h"
#import "QWForRegCell.h"
#import "QWLoginButtonCell.h"
#import "QWForgetController.h"
#import "QWRegisterController.h"
#import "EMDemoOptions.h"

@interface QWLoginController ()<UITableViewDelegate,UITableViewDataSource>
{
    BOOL _isAgree;
}
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation QWLoginController

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"登陆/注册";
    
    [self tableView];
}

- (UITableView *)tableView{
    if(!_tableView){
        _tableView =[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableView.estimatedRowHeight = 400;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedSectionFooterHeight=0;
        _tableView.estimatedSectionHeaderHeight=0;
        _tableView.showsVerticalScrollIndicator=NO;
        _tableView.showsHorizontalScrollIndicator=NO;
        
        _tableView.delegate =self;
        _tableView.dataSource =self;
        
        [_tableView registerNib:[UINib nibWithNibName:@"QWLoginCell" bundle:nil] forCellReuseIdentifier:@"QWLoginCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"QWForRegCell" bundle:nil] forCellReuseIdentifier:@"QWForRegCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"QWLoginButtonCell" bundle:nil] forCellReuseIdentifier:@"QWLoginButtonCell"];
        
        _tableView.backgroundColor=Color_TableView_Gray;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;

        
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        
    }
    return _tableView;
}


#pragma mark- UITableViewDelegate,UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0000001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.0000001;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == 0) {
        QWLoginCell *cell =[tableView dequeueReusableCellWithIdentifier:@"QWLoginCell"];
        return cell;
    }
    else if (indexPath.row ==1){
        QWForRegCell *cell =[tableView dequeueReusableCellWithIdentifier:@"QWForRegCell"];
        cell.superVC = self;
        cell.forgetClickBlock = ^{
            [self junmpToForgetPage];
        };
        cell.registClickBlock = ^{
            [self jumpToRegisterPage];
        };
        cell.agreementClickBlock = ^(BOOL isAgree) {
            self->_isAgree = isAgree;
        };

        return cell;
    }
    else if (indexPath.row ==2){
        QWLoginButtonCell *cell =[tableView dequeueReusableCellWithIdentifier:@"QWLoginButtonCell"];
        cell.loginClickBlock = ^{
            [self login];
        };
        return cell;
    }
    else{
        static NSString *CMainCell = @"CMainCell";
           UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CMainCell];
           if (cell == nil) {
               cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier: CMainCell];
           }
           return cell;
    }
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.view endEditing:YES];
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

#pragma mark - 进入忘记密码页面
- (void)junmpToForgetPage{
    QWForgetController *vc =[[QWForgetController alloc]init];
    UITextField *phoneField =(UITextField *)[_tableView viewWithTag:1];
    vc.phone = phoneField.text;
    __weak __typeof(self) weakSelf = self;
    vc.forgetSuccessBlock = ^(NSString * _Nonnull phone, NSString * _Nonnull pwd) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        UITextField *phoneField =(UITextField *)[strongSelf.tableView viewWithTag:1];
        UITextField *passwordField =(UITextField *)[strongSelf.tableView viewWithTag:2];
        phoneField.text = phone;
        passwordField.text = pwd;
    };
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 进入注册页面
- (void)jumpToRegisterPage{
    QWRegisterController *vc =[[QWRegisterController alloc]init];
    __weak __typeof(self) weakSelf = self;
    vc.registSuccessBlock = ^(NSString * _Nonnull phone, NSString * _Nonnull pwd) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        UITextField *phoneField =(UITextField *)[strongSelf.tableView viewWithTag:1];
        UITextField *passwordField =(UITextField *)[strongSelf.tableView viewWithTag:2];
        phoneField.text = phone;
        passwordField.text = pwd;
    };
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 登录请求
- (void)login{
    UITextField *phoneField =(UITextField *)[_tableView viewWithTag:1];
    UITextField *passwordField =(UITextField *)[_tableView viewWithTag:2];
    
    if (IsStringEmpty(phoneField.text)) {
        [SWHUDUtil hideHudViewWithMessageSuperView:self.view withMessage:@"请输入手机号!"];
        return;
    }
    if (IsStringEmpty(passwordField.text)) {
        [SWHUDUtil hideHudViewWithMessageSuperView:self.view withMessage:@"请输入密码!"];
        return;
    }
    
    if(!_isAgree){
        [SWHUDUtil hideHudViewWithMessageSuperView:self.view withMessage:@"请先勾选协议!"];
        return;
    }
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:phoneField.text forKey:@"userName"];
    [dic setValue:passwordField.text forKey:@"password"];
    
    [SWHUDUtil showHudViewInSuperView:self.view withMessage:@"请等待"];
    HXGetRequest * request = [[HXGetRequest alloc] initWithRequestUrl:URL_login argument:dic];
    [request startWithCompletionBlockWithSuccess:^(__kindof HXRequest *request, NSDictionary *result, BOOL success) {
        if (success) {
            if([result[@"result"] isEqualToString:@"login_ok"]){
                [SWHUDUtil hideHudView];
                NSDictionary *dic = result[@"data"];
                AppProfile.qaUserInfo = [QWqaUserModel mj_objectWithKeyValues:dic];
                [AppProfile saveUserDefault:AppProfile.qaUserInfo ];
                [self loginIM:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:QWLogin_Change_State object:nil];
                [self.navigationController popToRootViewControllerAnimated:YES];
            }else {
                NSString *msg = result[@"msg"];
                [SWHUDUtil hideHudViewWithFailureMessage:msg];
            }
        }else
        {
            [SWHUDUtil hideHudViewWithFailureMessage:@"网络异常，请重试！"];
        }
    } failure:^(__kindof HXRequest *request, NSString *errorInfo) {
        //错误
        NSLog(@"%@",errorInfo);
        [SWHUDUtil hideHudView];
    }];
}

#pragma mark - IM登录注册
- (void)loginIM:(BOOL)isCheckRegist{
    //备注：重点username不能有大写，否则用户其他信息（昵称、头像等）无法更新上去
    [[EMClient sharedClient] loginWithUsername:[AppProfile.qaUserInfo.id lowercaseString] password:@"0000" completion:^(NSString * _Nonnull aUsername, EMError * _Nullable aError) {
        if (!aError) {
            //更新用户环信信息
            [[[EMClient sharedClient] userInfoManager] updateOwnUserInfo:AppProfile.qaUserInfo.name withType:EMUserInfoTypeNickName completion:^(EMUserInfo* aUserInfo,EMError *aError) {
                        if(!aError) {
                            [[UserInfoStore sharedInstance] setUserInfo:aUserInfo forId:[EMClient sharedClient].currentUsername];
                            [[NSNotificationCenter defaultCenter] postNotificationName:USERINFO_UPDATE  object:nil];
                        }else{
                            dispatch_sync(dispatch_get_main_queue(), ^{
                                NSLog(@"失败");
                            });
                        }
                    }];


            // 设置自动登录
            [[EMClient sharedClient].options setIsAutoLogin:YES];
            NSLog(@"登录成功-----");
            EMDemoOptions *options = [EMDemoOptions sharedOptions];
            options.isAutoLogin = YES;
            options.loggedInUsername = AppProfile.qaUserInfo.id;
            options.loggedInPassword = @"0000";
            [options archive];
            //发送自动登录状态通知
            [[NSNotificationCenter defaultCenter] postNotificationName:ACCOUNT_LOGIN_CHANGED object:[NSNumber numberWithBool:YES]];
        } else {
            NSLog(@"登录失败----%@", aError.errorDescription);
            
            if(aError.code == 204&&isCheckRegist){
                [self registIM];
            }
        }
    }];
}
- (void)registIM{
    [[EMClient sharedClient] registerWithUsername:[AppProfile.qaUserInfo.id lowercaseString] password:@"0000" completion:^(NSString * _Nonnull aUsername, EMError * _Nullable aError) {
        if (!aError) {
            [self loginIM:NO];
        }
    }];
}


@end

